import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import curve_fit


# 定义多元函数
# def func(x, a, b, c):
#     return a * np.sin(b * x) + c

def func(x, a, b, c):
    return a * np.exp(-b * x) + c

# xdata = np.linspace(0, 4, 50)
# y = func(xdata, 2.5, 1.3, 0.5)
# rng = np.random.default_rng()
# y_noise = 0.2 * rng.normal(size=xdata.size)
# ydata = y + y_noise

# 生成随机数据
xdata = np.linspace(0, 10, 100)
y = func(xdata, 2.5, 1.3, 0.5)
np.random.seed(1729)
y_noise = 0.2 * np.random.normal(size=xdata.size)
ydata = y + y_noise

plt.plot(xdata, ydata, 'b-', label='data')

popt, pcov = curve_fit(func, xdata, ydata)
print(popt)

# array([2.56274217, 1.37268521, 0.47427475])
plt.plot(xdata, func(xdata, *popt), 'r-',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))


popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))
popt
# array([2.43736712, 1.        , 0.34463856])
plt.plot(xdata, func(xdata, *popt), 'g--',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))


plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()


# # 生成随机数据
# xdata = np.linspace(0, 10, 100)
# y = func(xdata, 1, 2, 3)
# np.random.seed(1729)
# y_noise = 0.2 * np.random.normal(size=xdata.size)
# ydata = y + y_noise

# # 进行多元函数拟合
# p = np.polyfit(xdata, ydata, 2)
# a, b, c = p

# # 进行多元函数拟合
# popt, pcov = curve_fit(func, xdata, ydata)
# a, b, c = popt

# plt.plot(func(xdata, 1, 2, 3), "r")
# plt.plot(func(xdata, a, b, c), "g")
# plt.show()

# # 输出拟合结果
# print("a =", a)
# print("b =", b)
# print("c =", c)
